package com.vm.utils;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.vm.model.AppType;
import com.vm.model.Scene;
import com.vm.model.Soft;

/**
 * 
 * @ProjectName: [WeiMai]
 * @Author: [kent.wang]
 * @CreateDate: [2015年1月26日 下午4:15:16]
 * @Version: [v1.0]
 * 
 */
public class JsonUtils2 {

	private static final String TAG = "JsonUtils";

	public <T> List<T> jsonToBean(JSONArray jsonArray) {

		List<T> list = new ArrayList<T>();

		return list;
	}

	public static <T> T jsonToBean(JSONObject jsonObject, Class<T> clazz) {
		return jsonToBean(jsonObject,clazz,null,null);
	}
	
	
	public static <T> T jsonToBean(JSONObject jsonObject, Class<T> clazz,String listAttrName,Class<T> childClass) {

		T t = null;

		try {
			t = clazz.newInstance();
			Field[] fields = t.getClass().getDeclaredFields();
			int count = jsonObject.length();

			Iterator<String> it = jsonObject.keys();
			List<String> columnName = new ArrayList<>();
			while (it.hasNext()) {
				columnName.add(it.next());
			}

			String fieldName = null;
			for (Field field : fields) {

				fieldName = field.getName();

				try {
					for (String key : columnName) {

						/**
						 * 赋值条件
						 * 1.key值和当前遍历的值一直
						 * 2.json中对应的值不能为null
						 * 3.json中对应的值不能为[]  (List为空)
						 * 4.json中对应的值不能为{}  (实体类对象为空)
						 */
						if (key.toLowerCase().equals(fieldName.toLowerCase())) {
							if (jsonObject.getString(key) != null&&!jsonObject.getString(key).equals("null")&&
									!jsonObject.getString(key).equals("[]")&&!jsonObject.getString(key).equals("{}")) {
								
								/**
								 * 处理sceneList
								 */
								if(listAttrName!=null){
									if (key.equals(listAttrName)) {
										JSONArray childArray = jsonObject
												.getJSONArray(key);

										List<T> childClassList = new ArrayList<T>();
										for (int i = 0; i < childArray.length(); i++) {
											try {
												JSONObject sceneObject = childArray
														.getJSONObject(i);
												T t1 = null;
												t1 = childClass.newInstance();
												
												t1 = (T) JsonUtils2.jsonToBean(
														sceneObject, t1.getClass());
												childClassList.add(t1);		

											} catch (JSONException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											}
										}
										
										String methodName = "set"
												+ fieldName.substring(0, 1)
														.toUpperCase()
												+ fieldName.substring(1);

										Method method = t.getClass()
												.getDeclaredMethod(
														methodName,
														field.getType());

										method.invoke(t, childClassList);
										columnName.remove(key);
										break;
									}
									
								}
								
								
								if (key.equals("type")) {
									JSONObject typeObject = jsonObject.getJSONObject(key);
									AppType type = JsonUtils2.jsonToBean(
											typeObject, AppType.class);
									String methodName = "set"
											+ fieldName.substring(0, 1)
													.toUpperCase()
											+ fieldName.substring(1);

									Method method = t.getClass()
											.getDeclaredMethod(
													methodName,
													field.getType());

									method.invoke(t, type);
									columnName.remove(key);
									break;
								}

								String methodName = "set"
										+ fieldName.substring(0, 1)
												.toUpperCase()
										+ fieldName.substring(1);

								Method method = t.getClass().getDeclaredMethod(
										methodName, field.getType());

								method.invoke(
										t,
										typeUtil(field.getType(), jsonObject
												.getString(field.getName())
												.toString()));

							}
							columnName.remove(key);
							break;
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					Log.e(TAG, fieldName+":"+ e.getMessage());
					continue;
				}

			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return t;
	}

	/**
	 * <b>基本数据类型转换</b>
	 * 
	 * @param clazz
	 * @param str
	 * @return Object
	 */
	// @SuppressWarnings("unchecked")
	private static Object typeUtil(Class<?> clazz, String str) {

		SimpleDateFormat smp = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

		if (clazz == Integer.class || clazz.getName().equalsIgnoreCase("int")) {
			return Integer.parseInt(str);
		} else if (clazz == Date.class
				|| clazz.getName().equalsIgnoreCase("Date")) {
			Date d = null;
			try {
				d = smp.parse(str);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return d;
		} else if (clazz == Double.class
				|| clazz.getName().equalsIgnoreCase("Double")) {

			return Double.parseDouble(str);
		} else if (clazz == Float.class
				|| clazz.getName().equalsIgnoreCase("float")) {

			return Float.parseFloat(str);
		} else if (clazz == Long.class
				|| clazz.getName().equalsIgnoreCase("long")) {

			return Long.parseLong(str);
		} else if (clazz == Short.class
				|| clazz.getName().equalsIgnoreCase("Short")) {

			return Short.parseShort(str);

		} else if (clazz == Boolean.class
				|| clazz.getName().equalsIgnoreCase("boolean")) {

			return Boolean.parseBoolean(str);

		}
		return str;
	}

}
